#include "completertextedit.h"
#include "login.h"
#include "mainui.h"
#include "ui_mainui.h"

#include <QCompleter>
#include <QDir>
#include <QFileInfoList>
#include <QFileInfoList>
#include <QFileInfoList>
#include <QGraphicsDropShadowEffect>
#include <QStandardItemModel>
#include <QTextCodec>
#include <QTextEdit>
#include <qtextedit.h>
#include "mydialog.h"
mainUI::mainUI(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::mainUI)
{
    /** test **/
//    User1::instance()->setUserName("lyy");
//    User1::instance()->globalManager.readUser();
    User1::instance()->backUp.readUser();
//    int i = 0;
//    for(auto each:User1::instance()->globalManager.users){
//        if(User1::instance()->globalManager.users[i].username == User1::instance()->username.toStdString()){
//             User1::instance()->setUserIndex(i);
//        }
//        i++;
//    }





    ui->setupUi(this);
    beautify_UI();
    ui->treeView->setEditTriggers(QTreeView::NoEditTriggers);//设置单元格不能编辑
    ui->treeView->setSelectionBehavior(QTreeView::SelectItems);//设置一次选中一个item
    ui->treeView->setFocusPolicy(Qt::NoFocus);//去掉鼠标移动到单元格上的虚线框
    ui->treeView->header()->setStretchLastSection(true);//设置最后一行自适应
    ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);

    init_treeView();
    init_tableView();
    //this->setStyleSheet("background-color: rgb(255, 255, 255);");
    //qDebug()<< "文件路径" << QApplication::applicationDirPath() + "/" + User::instance()->getUserName() + "/" + table_name + ".db_table";
//    std::cout<< "userIndex" <<User1::instance()->getUserIndex()<<std::endl;
    //std::cout<< "userdata" <<User1::instance()->globalManager.users[User1::instance()->userIndex].tables[0].data.rows.at(0).columns[0]<<std::endl;


//    mydialog* d = new mydialog(this,"添加属性时，不能单独存在not null");
//    d->show();

}

mainUI::~mainUI()
{
    delete ui;
}

void mainUI::beautify_UI(){
    this->setStyleSheet("border-radius:8px;");
    this->setAttribute(Qt::WA_TranslucentBackground, true);
    //设置无边框
    this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
    //实例阴影shadow
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    //设置阴影距离
    shadow->setOffset(0, 0);
    //设置阴影颜色
    shadow->setColor(QColor("#444444"));
    //设置阴影长度
    shadow->setBlurRadius(20);
    //给嵌套QWidget设置阴影
    ui->centralwidget->setGraphicsEffect(shadow);

    //给垂直布局器设置边距(此步很重要, 设置宽度为阴影的宽度)
    //这个边距会影响最大化的效果，如果想要最大化窗体的时候，需要重新设为0




    /** 美化treeView **/
    ui->treeView->setStyleSheet("background-color: rgb(0, 0, 0);");
    ui->treeView->setStyleSheet("border-radius:8px;");
    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
    shadow_effect->setOffset(0, 0);
    //阴影颜色
    shadow_effect->setColor(QColor(38, 78, 119, 127));
    //阴影半径
    shadow_effect->setBlurRadius(22);
    ui->treeView->setGraphicsEffect(shadow_effect);

    /** 美化tableView **/
    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect1 = new QGraphicsDropShadowEffect(this);
    shadow_effect1->setOffset(0, 0);
    //阴影颜色
    shadow_effect1->setColor(QColor(38, 78, 119, 127));
    //阴影半径
    shadow_effect1->setBlurRadius(22);
    ui->tableView->setStyleSheet("background-color: rgb(0, 0, 0);");
    ui->tableView->setStyleSheet("border-radius:8px;");
    ui->tableView->setGraphicsEffect(shadow_effect1);

//    /** 美化textEdit **/
//    //设置具体阴影
//    QGraphicsDropShadowEffect *shadow_effect2 = new QGraphicsDropShadowEffect(this);
//    shadow_effect2->setOffset(0, 0);
//    //阴影颜色
//    shadow_effect2->setColor(QColor(38, 78, 119, 127));
//    //阴影半径
//    shadow_effect2->setBlurRadius(22);
//    ui->textEdit->setStyleSheet("background-color: rgb(0, 0, 0);");
//    ui->textEdit->setStyleSheet("border-radius:8px;");
//    ui->textEdit->setGraphicsEffect(shadow_effect2);

    /** 美化底部界面 **/
    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect3 = new QGraphicsDropShadowEffect(this);
    shadow_effect3->setOffset(0, 0);
    //阴影颜色
    shadow_effect3->setColor(QColor(196, 196, 196, 150));
    //阴影半径
    shadow_effect3->setBlurRadius(22);
    //ui->label_3->setStyleSheet("background-color: rgb(0, 0, 0);");
    ui->plainTextEdit->setStyleSheet("border-radius:20px;");
    ui->plainTextEdit->setGraphicsEffect(shadow_effect3);








    textEdit = new CompleterTextEdit;

    QStringList stringList;
    stringList << "select" << "SELECT"<<"update"<<"UPDATE"<<"delete"<<"DELETE"<<"insert"<<"INSERT"<< "create" << "CREATE"<< "DROP" << "drop" << "alter" << "ALTER" << "MODIFY" << "modify"
                  << "TABLE" << "table" << "primary key" << "PRIMARY KEY" << "UNIQUE" << "unique" << "not null" << "NOT NULL" << "check" << "CHECK"<< "values" << "VALUES" << "from" << "FROM"
                  << "between" << "into" << "where" << "BETWEEN" << "INTO" << "WHERE" << "like" << "LIKE" << "SET" << "set";
    stringList.sort();
    QCompleter *completer = new QCompleter(stringList, textEdit);
    textEdit->setCompleter(completer);
    textEdit->setParent(this);
    textEdit->move(340,100);
    textEdit->resize(521,141);
    /** 美化textEdit **/
    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect2 = new QGraphicsDropShadowEffect(this);
    shadow_effect2->setOffset(0, 0);
    //阴影颜色
    shadow_effect2->setColor(QColor(38, 78, 119, 127));
    //阴影半径
    shadow_effect2->setBlurRadius(22);
    textEdit->setStyleSheet("background-color: rgb(0, 0, 0);");
    textEdit->setStyleSheet("border-radius:8px;");
    textEdit->setGraphicsEffect(shadow_effect2);
    SyntaxHighlighter *highlighter = new SyntaxHighlighter(textEdit->document());
    QString qsTextViewStyle = "color: #73A2AC;font-size:16px;font-family:Microsoft YaHei UI;font-weight:bold";
    textEdit->setStyleSheet(qsTextViewStyle);

//    QStringList words;
//    words<<"123456"<<"234567"<<"345678"<<"456789";

//    QCompleter *completer = new QCompleter(words, this);
//    //默认从头开始匹配，MatchContains设置为任意位置匹配
//    completer->setFilterMode(Qt::MatchContains);

//    ui->lineEdit->setCompleter(completer);
//    ui->textEdit->setTextColor(QColor(115,162,172,255));
}

//勿删！！！！QT的神奇bug
void mainUI::on_add_column_button_2_clicked(){

};

void mainUI::init_treeView(){


    //qDebug()<< QApplication::applicationDirPath();
    QString a = qApp->applicationDirPath()+ "/" + "User'sTableInfo" + "/" + User1::instance()->getUserName();
    //获取相对路径下所有.qb为后缀的文件名，即获取所有表的文件名
    QFileInfoList InfoList = QDir(qApp->applicationDirPath()+ "/" + "User'sTableInfo"
                                  + "/" + User1::instance()->getUserName()).entryInfoList();//获取当前目录所有文件
    QFileInfoList fileNameList;//定义放提取文件的List
    //遍历所有文件
    foreach(QFileInfo fileInfo, InfoList)
    {
        if(!fileInfo.isFile()) continue;//不是文件继续，只用于加速，可不加
    //后缀不区分大小写，需要区分直接用“==”
//        QRegExp find_name("(\\w+)Data");
//        find_name.indexIn(QString(fileInfo.baseName()));
//        QString name = find_name.cap(1);

        if(0==fileInfo.baseName().right(4).compare("Data") )
        {
            if(fileInfo.baseName() != ""){
                fileNameList << fileInfo;//指定后缀，加入列表
                qDebug() << fileInfo.baseName();
            }

        }
    }




    /** 以下是构建树形结构代码 **/
    QStandardItemModel *model = new QStandardItemModel(this);//构建模型
    ui->treeView->header()->setSectionResizeMode(QHeaderView::Stretch);
    model->setHorizontalHeaderLabels(QStringList(QStringLiteral("database")));//设置头部标签
    ui->treeView->setModel(model);//导入模型
    //ui->treeView->setModel(model);//设置model
    ui->treeView->expandAll();//设置展开
//    // 创建根节点，抽象Item，并没有实际数据
//    QStandardItem* itemRoot = model->invisibleRootItem();

    //创建第一个子节点数据
    QStandardItem *item = new QStandardItem(User1::instance()->getUserName());//创建一个条目对象
    qDebug() << "username3 : ";
    model->appendRow(item);//通过模型对象添加这个条目
    item->setIcon(QIcon(":/database_ico.ico"));//添加图标

    //创建表的树形结构
    for (int i = 0; i < fileNameList.size(); i ++) {
        QStandardItem *item1 = new QStandardItem(fileNameList.at(i).baseName().left(fileNameList.at(i).baseName().length()-4));//创建一个条目对象
        item1->setIcon(QIcon(":/table_ico.ico"));//添加图标
        item->appendRow(item1);
    }

}

void mainUI::init_tableView(){


    QStandardItemModel* table_model = new QStandardItemModel(this);//构建模型
    QItemSelectionModel* table_SelectModel = new QItemSelectionModel(table_model);
    ui->tableView->setModel(table_model);   //将tableview设置成model这个标准条目模型的模板, model设置的内容都将显示在tableview上
    connect(table_model, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(on_dataChanged(QModelIndex,QModelIndex,QVector<int>)));//连接更改的数据
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionModel(table_SelectModel);
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);

    attribute_num = 0;//初始化列的数量
    row_num = 0;//初始化行的数量
//    table_model->setHorizontalHeaderItem(0, new QStandardItem("姓名") );
//    table_model->setHorizontalHeaderItem(1, new QStandardItem("学号"));
//    table_model->setHorizontalHeaderItem(2, new QStandardItem("性别"));
//    table_model->setHorizontalHeaderItem(3, new QStandardItem("年龄"));
//    table_model->setHorizontalHeaderItem(4, new QStandardItem("院系"));
//    table_model->setHorizontalHeaderItem(5, new QStandardItem("兴趣"));
}

void mainUI::on_treeView_customContextMenuRequested(const QPoint &pos)
{

    QMenu* menu = new QMenu(ui->treeView);
    menu->addAction(QIcon(":/add_ico.ico"), QStringLiteral("添加"), this, SLOT(slotTreeMenuAdd(bool)));
    menu->addAction(QIcon(":/delete_ico.ico"),QStringLiteral("删除"), this, SLOT(slotTreeMenuDelete(bool)));
    menu->exec(ui->treeView->mapToGlobal(pos));
}

//点击两次树形结构的监听器
void mainUI::on_treeView_doubleClicked(const QModelIndex &index)
{



    attribute_num = 0;
    row_num = 0;
    QTextCodec *codec = QTextCodec::codecForName("GB2312");
    if(index.parent()==ui->treeView->rootIndex())
    {
        QStandardItemModel *tree_model = static_cast<QStandardItemModel*>(ui->treeView->model());
        tree_model->clear();
        init_treeView();
        qDebug()<<"first="<<index.data().toString();//只针对根节点有效
    }
    else if(index.parent().parent()==ui->treeView->rootIndex())//只针对二级节点有效
    {
       qDebug()<<"second="<<index.data().toString();
       table_name = index.data().toString();
       //清空数据
       QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
       table_model->clear();

       qDebug() << "here0" << endl;
       ui->add_row_button->setEnabled(true);
       ui->add_column_button->setEnabled(true);
       ui->delete_row_button->setEnabled(true);
       ui->delete_column_button->setEnabled(true);
       ui->query_button->setEnabled(true);


       /** 属性的写入操作 **/
       Operation p;
       QStringList linelist;
       UserManager a = User1::instance()
               ->globalManager;
       for (int i =0 ; i < User1::instance()
            ->globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].attributes.size(); i++) {
           linelist.append(QString::fromStdString(User1::instance()
                                                  ->globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].attributes[i].attriname));
       }



       qDebug() << linelist;
       init_attribute(linelist);

        int userIndex;
        for (int i =0;i<User1::instance()
             ->globalManager.users.size();i++) {
            if(User1::instance()
                    ->globalManager.users[i].username==User1::instance()->getUserName().toStdString()){
                userIndex = i;
                break;
            }
        }
        int tableIndex;
        for (int i =0;i<User1::instance()
             ->globalManager.users[userIndex].tables.size();i++) {
            if(User1::instance()
                    ->globalManager.users[userIndex].tables[i].tablename==table_name.toStdString()){
                tableIndex = i;
                break;
            }
        }
        QVector<QStringList> row_vector;
        for(auto row:User1::instance()
            ->globalManager.users[userIndex].tables[tableIndex].data.rows){
            QStringList list1;
            for(auto column:row.columns){
                QString temp = QString::fromStdString(column);
                list1.push_back(temp);
            }
            row_vector.push_back(list1);
        }



              /** 表内具体内容的写入操作 **/


//              while(!file.atEnd()){
//                  QString line = codec->toUnicode(file.readLine()).trimmed();
//                  QStringList linelist = line.split(" ");
//                  row_vector.append(linelist);
//                  qDebug() << linelist;
//                  if(linelist.isEmpty()){
//                      break;
//                  }
//              }
              init_row(row_vector);
              qDebug() << "初始属性2：" << attribute_num;
//       file.close();
    }
    else if(index.parent().parent().parent()==ui->treeView->rootIndex()) //只针对三级节点有效
    {
      qDebug()<<"third="<<index.data().toString();
    }

}

//删除表
void mainUI::slotTreeMenuDelete(bool checked)
{
    QStandardItemModel *model1 = static_cast<QStandardItemModel*>(ui->treeView->model());
    QModelIndex currentIndex = ui->treeView->currentIndex();//获取当前节点
    currentItem = model1->itemFromIndex(currentIndex);
     if(!currentItem->parent())
     {
         model1->removeRow(currentIndex.row());
         //currentItem->removeRows(0,currentItem->rowCount());
         //delete currentItem->takeRow(currentindex.row());
         return;
     }
    QStandardItem *parent = currentItem->parent();//获取当前节点的父节点
    parent->removeRow(currentIndex.row());  //通过当前节点的父节点删除当前节点
}

//创建文件

//添加新的表
void mainUI::slotTreeMenuAdd(bool checked){
    bool ok;
    // 获取字符串
    QString string = QInputDialog::getText(this, tr("添加表"), tr("请输入表名                  "), QLineEdit::Normal,tr(""), &ok);
    if(ok){
        qDebug() << "string:" << string;
        table_name = string; //将table_name设置为新建的表名
        QStandardItemModel *model1 = static_cast<QStandardItemModel*>(ui->treeView->model());
        QModelIndex currentIndex = ui->treeView->currentIndex();//获取当前节点
        currentItem = model1->itemFromIndex(currentIndex);
         if(!currentItem->parent())//如果点击的是无父节点的item，在本身的item下面添加（即直接在数据库下添加表）
         {
             QStandardItem *item1 = new QStandardItem(string);//创建一个条目对象
             qDebug() << "成功获取父节点";
             item1->setIcon(QIcon(":/table_ico.ico"));//添加图标
             currentItem->appendRow(item1);
             //currentItem->removeRows(0,currentItem->rowCount());
             //delete currentItem->takeRow(currentindex.row());
             return;
         }else{//如果点击的是有父节点的item，在本身的父节点的item下面添加（即直接在选择的item的父节点下添加表）
             QStandardItem *parent = currentItem->parent();//获取当前节点的父节点
             QStandardItem *item1 = new QStandardItem(string);//创建一个条目对象
             qDebug() << "成功获取父节点";
             item1->setIcon(QIcon(":/table_ico.ico"));//添加图标
             parent->appendRow(item1);
         }

         //创建文件
         QFile file(QApplication::applicationDirPath() + "/" + User1::instance()->getUserName() + "/" + table_name + ".db_table");
         if(!file.open(QIODevice::ReadWrite|QIODevice::Text)){
             qDebug()<<"文件打开失败";
         }
    }


}

//添加行的槽函数
void mainUI::on_add_row_button_clicked()
{
    Operation p;
    QList<QStandardItem*> list;
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    for (int i = 0;i < table_model->columnCount(); i++) {
        if(User1::instance()->globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].attributes[i].defaultValue=="null"){
            list.append(new QStandardItem("null"));
        }else {
            list.append(new QStandardItem(QString::fromStdString(User1::instance()->
                       globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].attributes[i].defaultValue)));
        }
    }

    qDebug()<<row_num;
    table_model->insertRow(row_num, list); //在第i行插入一条记录
    row_num++;



}

//初始化文件中读取的属性
void mainUI::init_attribute(QStringList list){
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    //table_model->clear();
    for (int i = 0;i < list.size(); i++) {
        attribute_num++;
        table_model->setHorizontalHeaderItem(i, new QStandardItem(list.at(i)));//添加一列
    }
//    qDebug() << "初始属性：" << attribute_num;
}

//初始化文件中读取的行
void mainUI::init_row(QVector<QStringList> row_vector){
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    //table_model->clear();
    int i = 0;
    for(auto first:row_vector){
        QList<QStandardItem*> list;

        for(auto second:first){
            list.append(new QStandardItem(second));
        }
        table_model->insertRow(i, list); //在第i行插入一条记录
        row_num++;
        i++;
    }
//    for (int i = 0;i < row_vector.size(); i++) {
//        QList<QStandardItem*> list;
//        for (int j = 0;j < row_vector.at(i).size(); j++) {
//            list.append(new QStandardItem(row_vector.at(i).at(j)));//在list中加入一行的item

//        }
//        table_model->insertRow(i, list); //在第i行插入一条记录
//        row_num++;
//    }
}


//新增一个属性
void mainUI::on_add_column_button_clicked()
{
    bool ok;
//    QString string = QInputDialog::getText(this, tr("新增列"),
//                                           tr("请输入列名                   "), QLineEdit::Normal,tr(""), &ok);//增加的属性名


    add_column_Dialog* d = new add_column_Dialog();
    d->show();

    connect(d, &add_column_Dialog::stop, this, [=](QString a, QString b) {
        QString ar_name;
        QString type_name;
        ar_name = a;
        type_name = b;
//        qDebug() << "attribute_num            " << attribute_num;
        QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
        if(table_model->headerData(0, Qt::Horizontal) == ""){
            attribute_num = 0;
            table_model->setHorizontalHeaderItem(attribute_num, new QStandardItem(ar_name));//添加一列
            for (int i = 0; i < table_model->rowCount() ; i++) {
                table_model->setData(table_model->index(i,table_model->columnCount()-1),"null");
            }
        }else{
            table_model->setHorizontalHeaderItem(attribute_num, new QStandardItem(ar_name));//添加一列
            for (int i = 0; i < table_model->rowCount() ; i++) {
                table_model->setData(table_model->index(i,table_model->columnCount()-1),"null");
            }
        }
            attribute_num++;
        Attribute attr;
        int type;
        if(type_name == "int"){
            type = 1;
        }else if(type_name == "float"){
            type = 2;
        }else if (type_name == "char"){
            type = 3;
        }else{
            type = 4;
        }
        User1::instance()->globalManager.users.at(User1::instance()->userIndex).addAttribute(table_name.toStdString(),ar_name.toStdString(), type,false,false,false,"null","null","null");

     });


}

//查询按钮的槽函数
void mainUI::on_query_button_clicked()
{



//    //清空数据
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    //table_model->clear();
//    QString query_attribute_name = "";
//    for (int i = 0; i < table_model->columnCount(); i ++) {
//        query_attribute_name = table_model->headerData(i, Qt::Horizontal).toString();
//        for (int j = 0; j < User1::instance()->globalManager.users[User1::instance()->userIndex].tables.size(); j++) {
//            if(User1::instance()->globalManager.users[User1::instance()->userIndex].tables[j].tablename == table_name.toStdString()){
//                User1::instance()->globalManager.users[User1::instance()->userIndex].tables[j].attributes[i].attriname = query_attribute_name.toStdString();
//            }
//        }
//    }
//    User1::instance()->globalManager.writeAttri(User1::instance()->getUserName().toStdString(), table_name.toStdString());
    //s << query_attribute_name << "\n";
//    qDebug() << "attribute" << query_attribute_name;

    //    bool addRecord(string tablename, vector<string> columnNames, vector<string> values); //指定列 添加一条记录

    vector<string> columnNames;
    vector<string> values;
    Operation p;
    UserManager a;
    a = User1::instance()->globalManager;
    User1::instance()->globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].data.rows.clear();
    for (int i = 0; i < table_model->rowCount(); i++) {
        QString line = "";
        columnNames.clear();
        values.clear();
        for (int j = 0; j < table_model->columnCount(); j ++) {
            QModelIndex index3 = table_model->index(i, j);      //获取选定的单元格的内容
            QString cell = table_model->data(index3).toString().trimmed();
            line = line + cell + " ";
            values.push_back(cell.toStdString());
            columnNames.push_back(table_model->headerData(j, Qt::Horizontal).toString().toStdString());
            qDebug() << "line: " <<line;

//            for (int m = 0; m < User1::instance()->globalManager.users[User1::instance()->userIndex].tables.size(); m++) {
//                if(User1::instance()->globalManager.users[User1::instance()->userIndex].tables[m].tablename == table_name.toStdString()){
//                       User1::instance()->globalManager.users[User1::instance()->userIndex].tables[m].data.rows[i].columns[j] = cell.toStdString();
//                }
//            }
        }
        if(!User1::instance()->globalManager.users[User1::instance()->userIndex].addRecord(table_name.toStdString(),columnNames,values)){
            QMessageBox::critical(this,"错误","更新数据违反约束条件");
            User1::instance()->globalManager = a;
        }


    }
    UserManager b;
    b = User1::instance()->globalManager;
    User1::instance()->globalManager.writeUser();
}

//删除一行
void mainUI::on_delete_row_button_clicked()
{
    qDebug()<<"点击按钮";
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    QModelIndex currentIndex = ui->tableView->currentIndex();//获取当前节点
    table_model->removeRow(currentIndex.row());
}

//神奇bug  勿删
void mainUI::on_delete_button_clicked()
{
    qDebug()<<"点击按钮";
}

void mainUI::on_pushButton_2_clicked()
{
    close();
}

void mainUI::on_delete_column_button_clicked()
{
    qDebug()<<"点击按钮";
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    QModelIndex currentIndex = ui->tableView->currentIndex();//获取当前节点
    table_model->removeColumn(currentIndex.column());

    Operation p;
    User1::instance()->globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].
            attributes.erase(User1::instance()->globalManager.users[User1::instance()->userIndex].tables[p.findTableIndex(table_name)].attributes.begin() + currentIndex.column());

    for (int j = 0; j < table_model->rowCount(); j++) {
        User1::instance()->globalManager.users[User1::instance()->userIndex].
                tables[p.findTableIndex(table_name)].data.rows[j].columns.erase(User1::instance()->globalManager.users[User1::instance()->userIndex].
                tables[p.findTableIndex(table_name)].data.rows[j].columns.begin() + currentIndex.column());
    }
    UserManager a = User1::instance()->globalManager;
    cout << "aaa";
}

void mainUI::on_switch_user_button_clicked()
{
    login* l = new login();
    l->show();
    close();
}

void mainUI::Table2ExcelByHtml(QTableView *table, QString title){
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    QString fileName = QFileDialog::getSaveFileName(table, "保存",QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),"Excel 文件(*.xls *.xlsx)");
    if (fileName!="")
    {
        QAxObject *excel = new QAxObject;
        if (excel->setControl("Excel.Application")) //连接Excel控件
        {
           excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体
           excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示
           QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
           workbooks->dynamicCall("Add");//新建一个工作簿
           QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
           QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);

           int i,j;
//           //QTablewidget 获取数据的列数
//           int colcount=table->columnCount();
//            //QTablewidget 获取数据的行数
//           int rowscount=table->rowCount()

           //QTableView 获取列数
      int colcount=table_model->columnCount();
           //QTableView 获取行数
      int rowcount=table_model->rowCount();

           QAxObject *cell,*col;
           //标题行
           cell=worksheet->querySubObject("Cells(int,int)", 1, 1);
           cell->dynamicCall("SetValue(const QString&)", title);
           cell->querySubObject("Font")->setProperty("Size", 18);
           //调整行高
           worksheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);
           //合并标题行
           QString cellTitle;
           cellTitle.append("A1:");
           cellTitle.append(QChar(colcount - 1 + 'A'));
           cellTitle.append(QString::number(1));
           QAxObject *range = worksheet->querySubObject("Range(const QString&)", cellTitle);
           range->setProperty("WrapText", true);
           range->setProperty("MergeCells", true);
           range->setProperty("HorizontalAlignment", -4108);//xlCenter
           range->setProperty("VerticalAlignment", -4108);//xlCenter
           //列标题
           for(i=0;i<colcount;i++)
           {
               QString columnName;
               columnName.append(QChar(i  + 'A'));
               columnName.append(":");
               columnName.append(QChar(i + 'A'));
               col = worksheet->querySubObject("Columns(const QString&)", columnName);
               col->setProperty("ColumnWidth", table->columnWidth(i)/6);
               cell=worksheet->querySubObject("Cells(int,int)", 2, i+1);
               //QTableWidget 获取表格头部文字信息
//               columnName=table->horizontalHeaderItem(i)->text();
               //QTableView 获取表格头部文字信息
                columnName=table_model->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString();
               cell->dynamicCall("SetValue(const QString&)", columnName);
               cell->querySubObject("Font")->setProperty("Bold", true);
               cell->querySubObject("Interior")->setProperty("Color",QColor(191, 191, 191));
               cell->setProperty("HorizontalAlignment", -4108);//xlCenter
               cell->setProperty("VerticalAlignment", -4108);//xlCenter
           }

          //数据区

          //QTableWidget 获取表格数据部分
//           for(i=0;i<rowcount;i++){
//               for (j=0;j<colcount;j++)
//               {
//                   worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", table->item(i,j)?table->item(i,j)->text():"");
//               }
//           }


          //QTableView 获取表格数据部分
            for(i=0;i<rowcount;i++) //行数
               {
                   for (j=0;j<colcount;j++)   //列数
                   {
                       QModelIndex index = table_model->index(i, j);
                       QString strdata = table_model->data(index).toString();
                       worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", strdata);
                   }
               }


           //画框线
           QString lrange;
           lrange.append("A2:");
           lrange.append(colcount - 1 + 'A');
           lrange.append(QString::number(table_model->rowCount() + 2));
           range = worksheet->querySubObject("Range(const QString&)", lrange);
           range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1));
           range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0));
           //调整数据区行高
           QString rowsName;
           rowsName.append("2:");
          rowsName.append(QString::number(table_model->rowCount() + 2));
          range = worksheet->querySubObject("Range(const QString&)", rowsName);
          range->setProperty("RowHeight", 20);
          workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName));//保存至fileName
          workbook->dynamicCall("Close()");//关闭工作簿
          excel->dynamicCall("Quit()");//关闭excel
          delete excel;
          excel=NULL;
          if (QMessageBox::question(NULL,"完成","文件已经导出，是否现在打开？",QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
          {
              QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
          }
      }
      else
      {
          QMessageBox::warning(NULL,"错误","未能创建 Excel 对象，请安装 Microsoft Excel。",QMessageBox::Apply);
      }
  }

}

void mainUI::on_export_button_clicked()
{
    Table2ExcelByHtml(ui->tableView, table_name + "表");
}


void mainUI::on_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    update_str = table_model->data(topLeft).toString();
    qDebug() << update_str ;
    QString attribute_name =  table_model->headerData(topLeft.column(), Qt::Horizontal).toString();
    QString sql = "update " + table_name + " set " +  attribute_name  + "= " + QString("'%1'").arg(update_str)
            + " where " + attribute_name + " = " + QString("'%1'").arg(current_str);

    send_sql.append(sql);
    qDebug() << sql;
}

void mainUI::on_tableView_doubleClicked(const QModelIndex &index)
{
    QStandardItem* aItem= static_cast<QStandardItemModel*>(ui->tableView->model())->itemFromIndex(index);
    current_str = aItem->text();
    qDebug() << current_str ;
}

void mainUI::on_pushButton_clicked()
{



    QStandardItemModel *table_model = static_cast<QStandardItemModel*>(ui->tableView->model());
    table_model->clear();
    QString sql = textEdit->toPlainText();

    UserManager a = User1::instance()->globalManager;
    Operation sql_parse(sql);
    if(sql_parse.operation_type=="commit"){
        User1::instance()->backUp = User1::instance()->globalManager;
        User1::instance()->globalManager.writeUser();
    }else if(sql_parse.operation_type=="rollBack"){
        User1::instance()->globalManager = User1::instance()->backUp;
        User1::instance()->globalManager.writeUser();
    }
    UserManager b = User1::instance()->globalManager;
    if(sql_parse.error_code != 0){
        if(sql_parse.error_code == 1){
//            QMessageBox::critical(this,"错误","错误的操作类型");
            mydialog* d = new mydialog(this,"错误的操作类型");
            d->show();
        }
        if(sql_parse.error_code == 2){
//            QMessageBox::critical(this,"错误","select语句没有from");
            mydialog* d = new mydialog(this,"select语句没有from");
            d->show();
        }
        if(sql_parse.error_code == 3){
//            QMessageBox::critical(this,"错误","插入语法有误");
            mydialog* d = new mydialog(this,"插入语法有误");
            d->show();
        }
        if(sql_parse.error_code == 4){
//            QMessageBox::critical(this,"错误","没有分号");
            mydialog* d = new mydialog(this,"没有分号");
            d->show();
        }
        if(sql_parse.error_code == 5){
//            QMessageBox::critical(this,"错误","插入时括号不全");
            mydialog* d = new mydialog(this,"插入时括号不全");
            d->show();
        }
        if(sql_parse.error_code == 6){
//            QMessageBox::critical(this,"错误","修改时出错");
            mydialog* d = new mydialog(this,"修改时出错");
            d->show();
        }
        if(sql_parse.error_code == 7){
//            QMessageBox::critical(this,"错误","创建表的语义出错");
            mydialog* d = new mydialog(this,"创建表的语义出错");
            d->show();
        }
        if(sql_parse.error_code == 8){
//            QMessageBox::critical(this,"错误","删除记录的语义出错");
            mydialog* d = new mydialog(this,"删除记录的语义出错");
            d->show();
        }
        if(sql_parse.error_code == 9){
//            QMessageBox::critical(this,"错误","解析列名时出错");
            mydialog* d = new mydialog(this,"解析列名时出错");
            d->show();
        }
        if(sql_parse.error_code == 10){
//            QMessageBox::critical(this,"错误","表结构修改的语义出错");
            mydialog* d = new mydialog(this,"表结构修改的语义出错");
            d->show();
        }
        if(sql_parse.error_code == 11){
//            QMessageBox::critical(this,"错误","删除表时出错");
            mydialog* d = new mydialog(this,"删除表时出错");
            d->show();
        }
        if(sql_parse.error_code == 12){
//            QMessageBox::critical(this,"错误","语句执行条件出错");
            mydialog* d = new mydialog(this,"语句执行条件出错");
            d->show();
        }
        if(sql_parse.error_code == 13){
//            QMessageBox::critical(this,"错误","UPDATA时的修改内容出错");
            mydialog* d = new mydialog(this,"UPDATA时的修改内容出错");
            d->show();
        }
        if(sql_parse.error_code == 14){
//            QMessageBox::critical(this,"错误","表没有找到");
            mydialog* d = new mydialog(this,"表没有找到");
            d->show();
        }
        if(sql_parse.error_code == 15){
//            QMessageBox::critical(this,"错误","表没有找到");
            mydialog* d = new mydialog(this,"表没有找到");
            d->show();
        }
        if(sql_parse.error_code == 16){
//            QMessageBox::critical(this,"错误","插入时列与值数量不匹配");
            mydialog* d = new mydialog(this,"插入时列与值数量不匹配");
            d->show();
        }
        if(sql_parse.error_code == 17){
//            QMessageBox::critical(this,"错误","插入时列与值的类型不匹配");
            mydialog* d = new mydialog(this,"插入时列与值的类型不匹配");
            d->show();
        }
        if(sql_parse.error_code == 18){
//            QMessageBox::critical(this,"错误","插入时顺序不对");
            mydialog* d = new mydialog(this,"插入时顺序不对");
            d->show();
        }
        if(sql_parse.error_code == 19){
//            QMessageBox::critical(this,"错误","where后面的运算符不对");
            mydialog* d = new mydialog(this,"where后面的运算符不对");
            d->show();
        }
        if(sql_parse.error_code == 20){
//            QMessageBox::critical(this,"错误","违反约束条件");
            mydialog* d = new mydialog(this,"违反约束条件");
            d->show();
        }
        if(sql_parse.error_code == 21){
//            QMessageBox::critical(this,"错误","create时，参数列表错误");
            mydialog* d = new mydialog(this,"create时，参数列表错误");
            d->show();
        }
        if(sql_parse.error_code == 22){
//            QMessageBox::critical(this,"错误","create时，类型错误");
            mydialog* d = new mydialog(this,"create时，参数列表错误");
            d->show();
        }
        if(sql_parse.error_code == 23){
//            QMessageBox::critical(this,"错误","create时，输入不存在的约束");
            mydialog* d = new mydialog(this,"create时，输入不存在的约束");
            d->show();
        }
        if(sql_parse.error_code == 24){
//            QMessageBox::critical(this,"错误","create时,主键不能设置默认值");
            mydialog* d = new mydialog(this,"create时,主键不能设置默认值");
            d->show();
        }
        if(sql_parse.error_code == 25){
//            QMessageBox::critical(this,"错误","添加属性时，不能单独存在not null");
            mydialog* d = new mydialog(this,"添加属性时，不能单独存在not null");
            d->show();
        }
        if(sql_parse.error_code == 26){
//            QMessageBox::critical(this,"错误","modify错误！");
            mydialog* d = new mydialog(this,"modify错误！");
            d->show();
        }
        if(sql_parse.error_code == 27){
//            QMessageBox::critical(this,"错误","add非空属性时必须给默认值！");
            mydialog* d = new mydialog(this,"add非空属性时必须给默认值！");
            d->show();
        }
    }else{
        if(sql_parse.operation_type=="select"){
            QStringList attri_list;
            QVector<QStringList> row_vector;
            QStringList cell_list;
            for (int i = 0; i < sql_parse.select_result[0].size(); i++) {
                attri_list.push_back(sql_parse.select_result[0][i]);
            }
            for (int j = 1; j < sql_parse.select_result.size(); j++ ) {
                QStringList cell_list;
                for (int i = 0; i < sql_parse.select_result[j].size(); i++) {
                    cell_list.push_back(sql_parse.select_result[j][i]);
                }
                row_vector.push_back(cell_list);
            }
            init_attribute(attri_list);
            init_row(row_vector);
        }

        Log log;
        string path = qApp->applicationDirPath().toStdString();
        string fileName = path + "//User'sTableInfo//" + User1::instance()->username.toStdString() + "Log.txt";
        cout << fileName << endl;
        log.createLog(fileName);
        log.writeLog(sql.toStdString());
    }

    if(sql_parse.operation_type == "create" || sql_parse.operation_type == "drop"){
        QStandardItemModel *tree_model = static_cast<QStandardItemModel*>(ui->treeView->model());
        tree_model->clear();
        init_treeView();
    }
    ui->add_row_button->setEnabled(false);
    ui->add_column_button->setEnabled(false);
    ui->delete_row_button->setEnabled(false);
    ui->delete_column_button->setEnabled(false);
    ui->query_button->setEnabled(false);
}




void mainUI::on_treeView_collapsed(const QModelIndex &index)
{

}

void mainUI::on_log_button_clicked()
{
    LogUI* l = new LogUI;
    l->show();
}
